import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import {
  Container,
  Grid,
  Card,
  CardContent,
  CardActions,
  Typography,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  IconButton,
  Box,
  Alert,
  CircularProgress
} from '@mui/material';
import {
  Add as AddIcon,
  Delete as DeleteIcon,
  Edit as EditIcon,
  Restore as RestoreIcon,
  Logout as LogoutIcon
} from '@mui/icons-material';
import axios from 'axios';

function Gallery() {
  const navigate = useNavigate();
  const { user } = useAuth();
  const [albums, setAlbums] = useState([]);
  const [open, setOpen] = useState(false);
  const [newAlbum, setNewAlbum] = useState({ name: '', description: '' });
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(true);
  const [editAlbum, setEditAlbum] = useState(null);

  const fetchAlbums = useCallback(async () => {
    try {
      setLoading(true);
      setError('');
      const response = await axios.get('/api/albums');
      setAlbums(response.data);
    } catch (error) {
      console.error('获取相册失败:', error);
      setError(error.response?.data?.message || '获取相册失败，请重试');
      if (error.response?.status === 401) {
        navigate('/login');
      }
    } finally {
      setLoading(false);
    }
  }, [navigate]);

  useEffect(() => {
    fetchAlbums();
  }, [fetchAlbums]);

  const handleCreateAlbum = async () => {
    try {
      await axios.post('/api/albums', newAlbum);
      setOpen(false);
      setNewAlbum({ name: '', description: '' });
      fetchAlbums();
    } catch (error) {
      console.error('创建相册失败:', error);
      setError(error.response?.data?.message || '创建相册失败，请重试');
    }
  };

  const handleDeleteAlbum = async (albumId) => {
    try {
      await axios.delete(`/api/albums/${albumId}`);
      fetchAlbums();
    } catch (error) {
      console.error('删除相册失败:', error);
      setError(error.response?.data?.message || '删除相册失败，请重试');
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    navigate('/login');
  };

  return (
    <Container maxWidth="lg" sx={{ mt: 4, mb: 4 }}>
      <Box sx={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        mb: 4,
        alignItems: 'center',
        flexDirection: { xs: 'column', sm: 'row' },
        gap: 2
      }}>
        <Typography variant="h4" component="h1" sx={{ 
          fontWeight: 600,
          color: 'primary.main'
        }}>
          我的相册
        </Typography>
        <Box sx={{ display: 'flex', gap: 2, flexDirection: { xs: 'column', sm: 'row' } }}>
          <Button
            variant="contained"
            startIcon={<AddIcon />}
            onClick={() => setOpen(true)}
            sx={{ 
              borderRadius: 2,
              textTransform: 'none',
              px: 3,
              width: { xs: '100%', sm: 'auto' }
            }}
          >
            新建相册
          </Button>
          <Button
            variant="outlined"
            startIcon={<RestoreIcon />}
            onClick={() => navigate('/trash')}
            sx={{ 
              borderRadius: 2,
              textTransform: 'none',
              px: 3,
              width: { xs: '100%', sm: 'auto' }
            }}
          >
            回收站
          </Button>
          <Button
            variant="outlined"
            color="error"
            startIcon={<LogoutIcon />}
            onClick={handleLogout}
            sx={{ 
              borderRadius: 2,
              textTransform: 'none',
              px: 3,
              width: { xs: '100%', sm: 'auto' }
            }}
          >
            退出登录
          </Button>
        </Box>
      </Box>

      {error && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {error}
        </Alert>
      )}

      {loading ? (
        <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
          <CircularProgress />
        </Box>
      ) : (
        <Grid container spacing={3}>
          {albums.map((album) => (
            <Grid item xs={12} sm={6} md={4} key={album._id}>
              <Card sx={{ 
                height: '100%',
                display: 'flex',
                flexDirection: 'column',
                transition: 'transform 0.2s',
                '&:hover': {
                  transform: 'translateY(-4px)',
                  boxShadow: 6
                }
              }}>
                <CardContent sx={{ flexGrow: 1 }}>
                  <Typography variant="h6" component="h2" sx={{ mb: 1 }}>
                    {album.name}
                  </Typography>
                  <Typography color="textSecondary" sx={{ 
                    display: '-webkit-box',
                    WebkitLineClamp: 3,
                    WebkitBoxOrient: 'vertical',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis'
                  }}>
                    {album.description || '暂无描述'}
                  </Typography>
                </CardContent>
                <CardActions sx={{ 
                  justifyContent: 'space-between',
                  px: 2,
                  pb: 2
                }}>
                  <Button
                    size="small"
                    color="primary"
                    onClick={() => navigate(`/album/${album._id}`)}
                    sx={{ textTransform: 'none' }}
                  >
                    查看
                  </Button>
                  <IconButton
                    size="small"
                    color="error"
                    onClick={() => handleDeleteAlbum(album._id)}
                  >
                    <DeleteIcon />
                  </IconButton>
                </CardActions>
              </Card>
            </Grid>
          ))}
        </Grid>
      )}

      <Dialog 
        open={open} 
        onClose={() => setOpen(false)}
        PaperProps={{
          sx: {
            borderRadius: 2,
            minWidth: 400
          }
        }}
      >
        <DialogTitle>新建相册</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            label="相册名称"
            fullWidth
            value={newAlbum.name}
            onChange={(e) => setNewAlbum({ ...newAlbum, name: e.target.value })}
            sx={{ mb: 2 }}
          />
          <TextField
            margin="dense"
            label="相册描述"
            fullWidth
            multiline
            rows={4}
            value={newAlbum.description}
            onChange={(e) => setNewAlbum({ ...newAlbum, description: e.target.value })}
          />
        </DialogContent>
        <DialogActions sx={{ px: 3, pb: 2 }}>
          <Button 
            onClick={() => setOpen(false)}
            sx={{ textTransform: 'none' }}
          >
            取消
          </Button>
          <Button 
            onClick={handleCreateAlbum} 
            variant="contained"
            disabled={!newAlbum.name.trim()}
            sx={{ 
              textTransform: 'none',
              px: 3
            }}
          >
            创建
          </Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
}

export default Gallery; 